package Swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

/*
    自定义类实现FocusListener,减少代码冗余
 */
public class FocusListenerDemo04 extends JFrame {
    public FocusListenerDemo04() throws HeadlessException {
        Toolkit toolkit= Toolkit.getDefaultToolkit();
        Dimension dimension=toolkit.getScreenSize();

        setBounds(dimension.width/4,dimension.height/4,dimension.width/2,dimension.height/2);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setVisible(true);
        Container container=getContentPane();
        container.setLayout(new FlowLayout());

        JTextField textField1=new JTextField(10);
        JTextField textField2=new JTextField(10);
        textField1.addFocusListener(new MyFocusListener());
        textField2.addFocusListener(new MyFocusListener());
        container.add(textField1);
        container.add(textField2);

        container.validate();
        setContentPane(container);
    }

    public static void main(String[] args) {
        FocusListenerDemo04 swing=new FocusListenerDemo04();
    }
}
class MyFocusListener implements FocusListener{

    @Override
    public void focusGained(FocusEvent e) {
        JTextField textField=(JTextField)e.getSource();
        textField.setBorder(BorderFactory.createLineBorder(Color.pink));        //创建一个边框，并指定颜色
    }

    @Override
    public void focusLost(FocusEvent e) {
        JTextField textField=(JTextField)e.getSource();
        textField.setBorder(BorderFactory.createLineBorder(Color.yellow));
    }
}
